<script setup lang="ts">
import {
  ElMessage,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput,
  FormRules,
  FormInstance
} from 'element-plus'
import { reactive, ref } from 'vue'

import { onMounted } from 'vue'
import { reqBindingDepartment } from '@/api/classify'

interface ClassificationForm {
  name: string
  department: string
  code: string
}

const rules = reactive<FormRules<ClassificationForm>>({
  department: [
    {
      required: true,
      message: '必须选择要绑定的责任单位',
      trigger: 'change'
    }
  ]
})

const formEl = ref<FormInstance>()

const props = defineProps({
  departments: {
    type: Object,
    required: true
  },
  currentRow: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['closeDialog'])

// 申请表单
const classificationForm = reactive<ClassificationForm>({
  code: props.currentRow.classificationCode,
  name: props.currentRow.classificationName,
  department: ''
})

const submitBinding = async () => {
  if (!formEl.value) return
  await formEl.value!.validate((valid, _fields) => {
    if (valid) {
      reqBindingDepartment(classificationForm.code, classificationForm.department).then((res) => {
        if (res) {
          ElMessage.success('绑定成功')
          emit('closeDialog')
        }
      })
    } else {
    }
  })
}

defineExpose({
  submitBinding
})

onMounted(() => {})
</script>

<template>
  <el-form
    ref="formEl"
    :model="classificationForm"
    label-width="auto"
    style="max-width: 450px"
    :rules="rules"
  >
    <el-form-item label="分类名称">
      <el-input v-model="classificationForm.name" readonly />
    </el-form-item>
    <el-form-item label="分类代码">
      <el-input v-model="classificationForm.code" readonly />
    </el-form-item>
    <el-form-item label="责任单位部门" prop="department">
      <el-select v-model="classificationForm.department" placeholder="请选择数据归属部门">
        <el-option
          v-for="item in Object.keys(departments).map((key) => ({
            label: departments[key],
            value: key
          }))"
          :key="item.label"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
  </el-form>
</template>
